import {Injectable} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd';
import {HttpService} from '@kylin/http';
import {UserService} from '@kylin/user';
import * as _ from 'lodash';

export class Option {
    name: string;               // 数据对应名称
    targetKey?: string;         // 一次获取多组数据时，生成结果中对应的key
    params?: any;               // 请求参数
    cache?: boolean;            // 是否缓存数据
    labelFrom?: string;         // label来自哪个属性
    valueFrom?: string;         // value来自哪个属性
}

@Injectable({
    providedIn: 'root',
})
export class DropdownDataService {
    dataSet: any = {};
    queryInfoMapping: any;

    constructor(private http: HttpService,
                private message: NzMessageService,
                private userService: UserService) {
        this.setDataSet();
        this.setQueryInfoMapping();
    }

    /** 获取一组数据 **/
    getData(option: Option): Promise<any> {
        const {name, params, cache, labelFrom, valueFrom} = option;
        return new Promise<any>((resolve, reject) => {
            if (this.dataSet[name] && cache) {
                resolve(this.dataSet[name]);
            } else if (this.queryInfoMapping[name]) {
                const queryInfo = this.queryInfoMapping[name];
                this.http.get(queryInfo.path, {...(queryInfo.params), ...params}).then(rep => {
                    if (rep.status === 200) {
                        const resultArr = Array.isArray(rep.result) ? rep.result : rep.result.records || [];
                        let dataSource = [];
                        if (queryInfo.processData) {
                            dataSource = queryInfo.processData(resultArr);
                        } else {
                            dataSource = resultArr.map(item => {
                                return {
                                    label: item[labelFrom || queryInfo.labelFrom || 'label'], // 参数->自定义->默认
                                    value: item[valueFrom || queryInfo.valueFrom || 'value'],
                                    key: item[labelFrom || queryInfo.labelFrom || 'label'],
                                    ...item
                                };
                            });
                        }
                        if (cache) {
                            this.dataSet[name] = dataSource;
                        } else {
                            this.dataSet[name] = void 0;
                        }
                        resolve(dataSource);
                    } else {
                        resolve([]);
                    }
                });
            } else {
                resolve([]);
            }
        });
    }

    /** 获取多组数据 **/
    getDataByGroup(options: Option[]) {
        const promiseArr = [];
        options.map(option => {
            promiseArr.push(this.getData(option));
        });
        return new Promise<any>(resolve => {
            Promise.all(promiseArr).then(rst => {
                const dataMapping: any = {};
                options.map((option, idx) => {
                    dataMapping[option.targetKey || option.name] = rst[idx];
                });
                resolve(dataMapping);
            });
        });
    }

    setDataSet() {
        const source = {
            year: (_.range(1970, new Date(this.userService.getValue('loginTime')).getFullYear() + 1)).reverse()
        };
        Object.keys(source).map(listName => {
            if (source[listName] && source[listName].length) {
                this.dataSet[listName] = source[listName].map(item => {
                    return {
                        label: item.label || item + '',
                        value: item.label || item + '',
                        key: item.label || item + ''
                    };
                });
            }
        });
    }

    setQueryInfoMapping() {
        this.queryInfoMapping = {
            grassItems: { // 涉及项目
                path: '/dataDict/pageList',
                params: {
                    type: 1
                },
                valueFrom: 'dataDictNo',
                labelFrom: 'name',
                current: 1,
                size: 9999
            },
            applyFertilizer: { // 施肥情况
                path: '/dataDict/pageList',
                params: {
                    type: 4
                },
                valueFrom: 'dataDictNo',
                labelFrom: 'name',
                current: 1,
                size: 9999
            },
            landTypeName: { // 地块类型
                path: '/dataDict/pageList',
                params: {
                    type: 2
                },
                valueFrom: 'dataDictNo',
                labelFrom: 'name',
                current: 1,
                size: 9999
            },
            useModeName: { // 利用方式
                path: '/dataDict/pageList',
                params: {
                    type: 3
                },
                valueFrom: 'dataDictNo',
                labelFrom: 'name',
                current: 1,
                size: 9999
            },
            cities: { // 城市列表， 参数: id：number | string
                path: '/cityManagement/cityByProvinceId',
                params: {},
                valueFrom: 'id',
                labelFrom: 'name',
            },
            areas: { // 区县列表， 参数: id：number | string
                path: '/cityManagement/areasByCityId',
                params: {},
                valueFrom: 'id',
                labelFrom: 'name',
            },
            allAreas: { // 所有区县列表， 参数: no
                path: '/cityManagement/allAreaByProvinceId',
                params: {},
                valueFrom: 'id',
                labelFrom: 'name',
            },
            countries: {
                path: '/cityManagement/countryPageList',
                params: {},
                valueFrom: 'id',
                labelFrom: 'name',
            },
            varietyAllLevel: { // 种质品种列表， 参数: no
                path: '/dataDict/varietyList',
                processData: (resultArr) => {
                    return resultArr;
                }
            },
            country: { // 乡名， 参数: no
                path: '/cityManagement/countryByAreaId',
                params: {},
                valueFrom: 'id',
                labelFrom: 'name'
            },
            /** 剔除没有子种名的科名项 **/
            variety: { // 种质品种列表， 参数: no
                path: '/dataDict/varietyList',
                processData: (resultArr) => {
                    const rst = [];
                    resultArr.map((type, index) => {
                        if (Array.isArray(type.children)) {
                            const tmpType = [];
                            let count = 0;
                            type.children.map(kind => {
                                if (!kind.isLeaf) {
                                    tmpType.push(kind);
                                } else {
                                    count++;
                                }
                            });
                            if (count !== type.children.length) {
                                type.children = tmpType;
                                rst.push(type);
                            }
                        }
                    });
                    return rst;
                }
            },
        };
    }

    /**
     * 获取年份下拉列表options选项,适用于动态表单的
     */
    fetchYearOptions(KeyName?: string, valueName?: string): any[] {
        const currentYear = new Date(this.userService.getValue('loginTime')).getFullYear();
        const years = _.range(1970, currentYear + 1).reverse();
        return years.map(i => {
            return {[KeyName ? `${KeyName}` : 'key']: i, [valueName ? `${valueName}` : 'value']: i};
        });
    }

    private fetchLocationOptions(path: string, targetValue, targetLabel, id?: string): Promise<any> {
        return new Promise((resolve, reject) => {
            this.http.get(path + id)
                .then(res => {
                    if (res.result) {
                        if (res.result.length === 0) {
                            resolve([]);
                        } else {
                            const data = res.result.map((i) => {
                                return {label: i[targetLabel], value: i[targetValue]};
                            });
                            resolve(data);
                        }
                    } else {
                        console.log('获取市区县信息失败');
                        console.log(res);
                    }
                })
                .catch(err => {
                    console.log('获取市区县信息失败');
                    console.log(err);
                });
        });
    }

    fetchCityOptions(): Promise<any[]> {
        const path = '/cityManagement/cityByProvinceId?size=99999';
        return this.fetchLocationOptions(path, 'id', 'name', '');
    }

    fetchAreaOptions(cityId: string): Promise<any[]> {
        const path = '/cityManagement/areasByCityId?size=99999&id=';
        return this.fetchLocationOptions(path, 'id', 'name', cityId);
    }

    fetchCountryOptions(areaId: string): Promise<any[]> {
        const path = '/cityManagement/countryByAreaId?size=99999&id=';
        return this.fetchLocationOptions(path, 'countryId', 'name', areaId);
    }

}


export const habitat = ['田边', '路旁', '阴坡', '阳坡', '沟谷', '湖边', '溪边', '海岸', '河岸', '沼泽', '林中', '林缘', '灌木', '固定沙丘', '流沙', '平坦地', '石质山坡'];
